package com.example.goodrubish.Fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.goodrubish.API.Okhttp_work;
import com.example.goodrubish.Garbage.DetailActivity1;
import com.example.goodrubish.Garbage.DetailActivity2;
import com.example.goodrubish.MusicService;
import com.example.goodrubish.R;
import com.example.goodrubish.Search;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchFragment extends Fragment {

//
    private ViewPager2 viewPager;
    private List<Integer> imageResources;
    private Runnable updateCurrentItem;
    private Handler handler;
//



    private EditText et_search;
    private Button bt_search,bt_play,bt_stop;
    public static JSONObject Search_JSON;
    //接口地址加密钥
    String url_garbage="http://api.tianapi.com/txapi/lajifenlei/index?key=8edca382d393d0c5f84996d0e8946b96&word=";

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SearchFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SearchFragment newInstance(String param1, String param2) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

//

    }

    //
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewPager = view.findViewById(R.id.view_pager);
//        LinearLayout pagerIndicator = view.findViewById(R.id.pager_indicator);

        imageResources = new ArrayList<>();
        imageResources.add(R.drawable.zhishi1);
        imageResources.add(R.drawable.zhishi2);
        imageResources.add(R.drawable.zhishi3);
        imageResources.add(R.drawable.zhishi4);

        viewPager.setAdapter(new SimplePagerAdapter(imageResources));

        // 设置自动滚动
        setupAutoScroll();

        // Inflate the layout for this fragment
        LinearLayout layoutItem1 = view.findViewById(R.id.layout_item_1);
        LinearLayout layoutItem2 = view.findViewById(R.id.layout_item_2);

        layoutItem1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到详情页
                Intent intent = new Intent(getActivity(), DetailActivity1.class);
                startActivity(intent);
            }
        });

        layoutItem2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到详情页
                Intent intent = new Intent(getActivity(), DetailActivity2.class);
                startActivity(intent);
            }
        });
    }

    private void initPagerIndicator(LinearLayout pagerIndicator) {
        pagerIndicator.removeAllViews();
        for (int i = 0; i < imageResources.size(); i++) {
            ImageView indicator = new ImageView(getContext());
            indicator.setScaleType(ImageView.ScaleType.CENTER);
//            indicator.setImageResource(R.drawable.indicator_inactive); // 未选中的指示器样式
            if (i == viewPager.getCurrentItem()) {
//                indicator.setImageResource(R.drawable.indicator_active); // 选中的指示器样式
            }
            pagerIndicator.addView(indicator);
        }

        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
//                updatePagerIndicator(position);
            }
        });
    }

//    private void updatePagerIndicator(int position) {
//        LinearLayout pagerIndicator = getView().findViewById(R.id.pager_indicator);
//        for (int i = 0; i < pagerIndicator.getChildCount(); i++) {
//            ImageView indicator = (ImageView) pagerIndicator.getChildAt(i);
//            indicator.setImageResource(i == position ? R.drawable.indicator_active : R.drawable.indicator_inactive);
//        }
//    }

    private void setupAutoScroll() {
        handler = new Handler(Looper.getMainLooper());
        updateCurrentItem = new Runnable() {
            @Override
            public void run() {
                int currentItem = viewPager.getCurrentItem();
                int itemCount = ((SimplePagerAdapter) viewPager.getAdapter()).getItemCount();
                viewPager.setCurrentItem((currentItem + 1) % itemCount, true);
                handler.postDelayed(this, 3000); // 每3秒切换一次
            }
        };
        handler.post(updateCurrentItem);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 停止自动滚动
        if (handler != null) {
            handler.removeCallbacks(updateCurrentItem);
        }
    }

    private class SimplePagerAdapter extends androidx.viewpager2.adapter.FragmentStateAdapter {

        private List<Integer> images;

        public SimplePagerAdapter(List<Integer> images) {
            super(SearchFragment.this);
            this.images = images;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return ImageSlideFragment.newInstance(images.get(position));
        }

        @Override
        public int getItemCount() {
            return images.size();
        }
    }

    public static class ImageSlideFragment extends Fragment {

        private int imageResId;

        public static ImageSlideFragment newInstance(int imageResId) {
            ImageSlideFragment fragment = new ImageSlideFragment();
            Bundle args = new Bundle();
            args.putInt("image_res_id", imageResId);
            fragment.setArguments(args);
            return fragment;
        }

        public ImageSlideFragment() {}

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                imageResId = getArguments().getInt("image_res_id");
            }
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_image_slide, container, false);
            ImageView imageView = view.findViewById(R.id.image_view);
            imageView.setImageResource(imageResId);
            return view;
        }
    }

    //



    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        et_search = getActivity().findViewById(R.id.et_search);
        bt_search = getActivity().findViewById(R.id.bt_search);
        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intn_search();
            }
        });

        bt_play = getActivity().findViewById(R.id.btn_play);
        bt_stop = getActivity().findViewById(R.id.btn_stop);
        Intent intent = new Intent(getActivity(), MusicService.class);
        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().startService(intent);
            }
        });
        bt_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().stopService(intent);
            }
        });
    }
    public void intn_search() {
        View view = getActivity().getWindow().peekDecorView();
        if (view != null) {//这里是网络访问的代码，获取服务
            InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        initData_search();
    }
    Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(getActivity(),"网络错误",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    String json=(String)msg.obj;
                    try{
                        Search_JSON=new JSONObject(json);
                        Intent intent=new Intent();
                        intent.setClass(getActivity(), Search.class);
                        startActivity(intent);		//进行页面跳转
                        break;
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
            return false;
        }
    });

    private void initData_search(){
        String data=et_search.getText().toString();
        if(TextUtils.isEmpty(data)){//如果内容为空，弹出toast消息，不为空则执行164行以后的代码
            Toast.makeText(getActivity(),"垃圾名称不能为空！",Toast.LENGTH_SHORT).show();
        }
        else{
            Okhttp_work.OkHttpGet(url_garbage+data, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String content=response.body().string();
                    Message message=new Message();
                    message.what=1;
                    message.obj=content;
                    handler_search.sendMessageDelayed(message,1000);
                }
            });
        }
    }
}